package com.sip.dbadapter.dao.impl;

import java.io.Serializable;
import java.util.List;

import com.sip.dbadapter.dao.domain.ApiDefinition;
import com.sip.dbadapter.dao.interfaces.ReferenceDataDao;

public class ReferenceDataDaoImpl extends BusinessDaoImpl<ApiDefinition, Serializable> implements ReferenceDataDao {

    @Override
    protected Class<ApiDefinition> getDomainClass() {

        return ApiDefinition.class;
    }

    /**
     * 
     */
    @Override
    public List<Object> getReferenceData(String propertyName) {

        List<Object> apiDefinitionDataList = (List<Object>) exec("select distinct A." + propertyName + " from " + getDomainClass().getName() + " A");

        return apiDefinitionDataList;
    }

    /**
     * 
     */
    @Override
    public List<Object[]> getReferenceData(String[] propertyName) {

        String propertyString = getPropertyStringValue(propertyName);

        System.out.println("==>" + "select distinct " + propertyString + " from " + getDomainClass().getName() + " A");
        List<Object[]> apiDefinitionDataList = (List<Object[]>) exec("select distinct " + propertyString + " from " + getDomainClass().getName() + " A");
        return apiDefinitionDataList;
    }

    /**
     * 
     */
    @Override
    public List<Object> getReferenceData(String propertyName, String[] conditionParamNames, Object[] paramsValues) {

        String conditionClause = "";

        conditionClause = createConditionClause(conditionParamNames, conditionClause);
        if (conditionParamNames.length > 1) {
            conditionClause = conditionClause.substring(4);// remove "and" at the begin.
        }
        System.out.println("==>" + conditionClause);
        System.out.println("==>" + "select A." + propertyName + " from " + getDomainClass().getName() + " A where ");
        List<Object> apiDefinitionDataList =
            (List<Object>) exec("select A." + propertyName + " from " + getDomainClass().getName() + " A where " + conditionClause, paramsValues);

        return apiDefinitionDataList;
    }

    private String getPropertyStringValue(String[] propertyName) {

        String propertyString = "";
        for (String object : propertyName) {
            if (propertyName.length == 1) {
                propertyString = "A." + object + " ";
            } else {
                propertyString += ",  A." + object;
            }
        }
        if (propertyName.length > 1) {
            propertyString = propertyString.substring(1);
        }

        return propertyString;
    }

    private String createConditionClause(String[] conditionParamNames, String conditionClause) {

        for (String object : conditionParamNames) {
            if (conditionParamNames.length == 1) {
                conditionClause = "A." + object + "=?";
            } else {
                conditionClause += " and A." + object + "=?";
            }
        }

        return conditionClause;
    }

}
